const jsonServer = require('json-server');
const uuid = require('node-uuid');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const low = require('lowdb');
const storage = require('lowdb/file-async');
const jwt = require('jsonwebtoken');

//创建一个Express服务器
const server = jsonServer.create();

//使用json-server默认选择的中间件（logger，static, cors和no-cache）
server.use(jsonServer.defaults());

//使用body-parser中间件
server.use(bodyParser.json());


//数据文件
const dbfile = process.env.prod === '1' ? 'db.json' : '_db.json';

//创建一个lowdb实例
const db = low(dbfile, {storage});

const RSA_PRIVATE_KEY = "kobuta-super-shared-secret";

const md5 = str => crypto
    .createHash('md5')
    .update(str.toString())
    .digest('hex');

// register
server.post('/user/add', (req, res) => {
  const item = req.body;
  const user = db('user')
      .find({
        username: item.username
      });
  if (user) {
    res.json({
      success: false,
      message: `"${item.username}" is exists`
    })
  } else {
    item.password = md5(item.password);
    item.createDate = new Date().toLocaleDateString();
    item.id = uuid.v1();
    db('user')
        .push(item)
        .then(() => {
          res.json({
            success: true
          });
        });
  }
});

// login
server.post('/login', (req, res) => {
  const data = req.body || {};
  const username = data.username;
  const user = db('user')
      .find({
        username
      });

  if (user && user.password === md5(data.password)) {
    // todo reset session
    res.json({
      success: true
    });
  } else {
    res.json({
      success: false,
      message: 'username or password error'
    });
  }
});


server.post('/auth', function(req, res) {
  const item = req.body;
  const user = db('user')
      .find({
        username: item.username
      });

  if (user && user.password === md5(item.password)) {
    var token = jwt.sign({userID: user.id,role: user.role}, RSA_PRIVATE_KEY, {expiresIn: '1h'});
    return res.send({token});
  }
  else {
    return res.sendStatus(401);
  }
});


server.post('/verify', function(req, res) {
  const item = req.body;
  jwt.verify(item.token, RSA_PRIVATE_KEY, function (err, decode) {
    if (err) {  //  时间失效的时候/ 伪造的token          
        res.send({'status':0});            
    } else {
        res.send({'status':1});
    }
  })
});


//路由配置
const router = jsonServer.router(dbfile);
server.use('/api', router);

//启动服务，并监听5000端口
server.listen(5000, () => {
  console.log('server is running at ', 5000, dbfile);
});
